﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.WebApi.Dtos;
using MyBlog.WebApi.Utility;
using MyBlog.WebApi.Utility.MDFive;

namespace MyBlog.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class WriterInfoController : ControllerBase
    {
        private readonly IWriterInfoService _writerInfoService;
        public WriterInfoController(IWriterInfoService writerInfoService)
        {
            this._writerInfoService = writerInfoService;
        }

        /// <summary>
        /// 创建作者
        /// </summary>
        /// <param name="name"></param>
        /// <param name="username"></param>
        /// <param name="userpwd"></param>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name, string username, string userpwd)
        {
            //数据验证
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(userpwd))
            {
                return ApiResultHelper.Error("数据不能为空");
            }

            WriterInfo writer = new WriterInfo
            {
                Name = name,
                UserName = username,
                //加密
                UserPwd = MD5Helper.MD5Encrypt32(userpwd)
            };
            var oldWriter = await _writerInfoService.FindAsync(u => u.UserName == username);
            if (oldWriter != null)
                return ApiResultHelper.Error("数据已存在");
            bool b = await _writerInfoService.CreateAsync(writer);
            if (!b)
                return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success(writer);

        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPut("Edit")]
        public async Task<ApiResult> Edit(string name)
        {
            int id = Convert.ToInt32(this.User.FindFirst("id").Value);
            var writer = await _writerInfoService.FindAsync(id);
            if (writer == null)
                return ApiResultHelper.Error("没有查询到数据");
            writer.Name = name;
            bool b = await _writerInfoService.EditAsync(writer);
            if (!b)
                return ApiResultHelper.Error("修改失败");
            return ApiResultHelper.Success(writer);
        }


        [HttpGet("FindWriter")]
        [AllowAnonymous]
        public async Task<ApiResult> FindWriter([FromServices] IMapper iMapper, int id)
        {
            var writer = await _writerInfoService.FindAsync(id);
            var writerDTO = iMapper.Map<WriterInfoDto>(writer);
            return ApiResultHelper.Success(writerDTO);
        }
    }
}
